package com.tsd.anon;

import com.alibaba.fastjson.JSON;
import com.tsd.CommonMsgNameConstants;
import com.tsd.common.controller.BaseController;
import com.tsd.core.constants.Constants;
import com.tsd.core.datasource.DataSourceContextHolder;
import com.tsd.core.openweixin.model.WechatMessageResult4AccessToken;
import com.tsd.core.utils.HlpUtils;
import com.tsd.core.utils.HttpUtil;
import com.tsd.core.utils.WebUtils;
import com.tsd.core.vo.ErrorCode;
import com.tsd.core.vo.HttpResult;
import com.tsd.openweixin.controller.OpenWeixinController;
import com.tsd.openweixin.entity.OpenWeixinSetting;
import com.tsd.system.controller.SysUserController;
import com.tsd.system.entity.SysAccountSetExt;
import com.tsd.system.entity.SysSettingExt;
import com.tsd.system.entity.SysUserExt;
import com.tsd.system.service.SysAccountSetService;
import com.tsd.system.service.SysSettingService;
import com.tsd.system.service.SysUserService;
import com.tsd.system.vo.OpenSetting;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;


/**
 * 描述：匿名读取数据的控制器
 * 未登录时需要获取数据的方法都写这里
 *
 * @author david
 * @date 2021/07/15 10:35:26
 */
@Controller
@Scope("prototype")
@RequestMapping("/anon")
@Api(tags = "匿名读取数据", description = "匿名读取数据的控制器")
public class AnonReadController extends BaseController {

    @Resource
    private SysSettingService sysSettingService;
    @Resource
    private SysUserService sysUserService;
    @Resource
    private SysUserController sysUserController;
    @Resource
    private SysAccountSetService sysAccountSetService;

    private static final WebUtils WEB_UTILS;

    static {
        WEB_UTILS = WebUtils.getInstance();
    }

    @ApiOperation(value = "微信开放平台设置", notes = "根据id获取设置（json）")
    @ApiImplicitParams({})
    @ResponseBody
    @RequestMapping(value = "/getWeixinOpenSetting.action", method = RequestMethod.POST)
    public HttpResult<Object> getWeixinOpenSetting() {
        HttpResult<Object> hr = new HttpResult<>();
        try {
            SysSettingExt query = new SysSettingExt();
            query.setCode(OpenSetting.SETTING_CODE_WX_OPEN);
            SysSettingExt sysSetting = sysSettingService.getSysSettingByCodeOwnerSid(query);
            if (sysSetting != null) {
                Map<String, Object> map = JSON.parseObject(sysSetting.getJson());
                Map<String, Object> ret = new HashMap<>(2);
                if ("1".equals(HlpUtils.getString(map, "login_wx"))) {
                    HlpUtils.copyStringValue(map, ret, "login_wx", "login_wx", false, false);
                    HlpUtils.copyStringValue(map, ret, "wx_open_appid", "wx_open_appid", false, false);
                    HlpUtils.copyStringValue(map, ret, "wx_open_redirect_url", "wx_open_redirect_url", false, false);
                }
                hr.setData(ret);
            }
            hr.setCode(ErrorCode.CODE_SUCCESS);
        } catch (Exception e) {
            super.procException(hr, e);
        }
        return hr;
    }

    @ApiOperation(value = "微信开放登录", notes = "")
    @ApiImplicitParams({})
    @ResponseBody
    @RequestMapping(value = "/wxLogin.action", method = RequestMethod.POST)
    public HttpResult<Object> wxLogin() {
        HttpResult<Object> hr = new HttpResult<>();
        try {
            long startTime = System.currentTimeMillis();
            Map<String, Object> map = super.getParams(request);
            SysSettingExt query = new SysSettingExt();
            query.setCode(OpenSetting.SETTING_CODE_WX_OPEN);
            SysSettingExt sysSetting = sysSettingService.getSysSettingByCodeOwnerSid(query);
            OpenWeixinSetting openWeixinSetting = JSON.parseObject(sysSetting.getJson(), OpenWeixinSetting.class);
            String code = HlpUtils.getString(map, "code");
            if (!HlpUtils.isEmpty(code)) {
                String url = String.format(OpenWeixinController.URL_ACCESS_TOKEN, openWeixinSetting.getWx_open_appid(), openWeixinSetting.getWx_open_app_secret(), code);
                String json = WEB_UTILS.getFromURL(url);
                WechatMessageResult4AccessToken result = JSON.parseObject(json, WechatMessageResult4AccessToken.class);
                if (result.isSuccess()) {
                    String openId = result.getOpenid();
                    SysUserExt user = sysUserService.getSysUserByOpenId(openId);
                    sysUserController.loginSuccess(user, startTime, map);
                    hr.setCode(ErrorCode.CODE_SUCCESS);
                    hr.setData(user);
                } else {
                    hr.setMessage(result.getErrcode() + "," + result.getErrmsg());
                }
            } else {
                hr.setMessage("缺少参数code");
            }
        } catch (Exception e) {
            super.procException(hr, e);
        }
        return hr;
    }

    @ApiOperation(value = "检查账套是否存在", notes = "")
    @ApiImplicitParams({})
    @ResponseBody
    @RequestMapping(value = "/checkAccountSet.action", method = RequestMethod.POST)
    public HttpResult<Object> checkAccountSet() {
        HttpResult<Object> hr = new HttpResult<>();
        try {
            Map<String, Object> map = super.getParams(request);
            String account_set_sid = HlpUtils.getString(map,"account_set_sid");
            super.checkEmpty(account_set_sid, CommonMsgNameConstants.getEmptyMsg(Constants.HEADER_NAME_ACCOUNT_SET_SID));
            if (DataSourceContextHolder.DEFAULT_ACCOUNT_SET_SID.equals(account_set_sid)) {
                hr.setCode(ErrorCode.CODE_SUCCESS);
            } else {
                DataSourceContextHolder.setDataSourceType(null);
                HttpResult<SysAccountSetExt> result = sysAccountSetService.checkSysAccountSetValid(account_set_sid);
                if (ErrorCode.CODE_SUCCESS != result.getCode()) {
                    return HttpResult.procError(result.getMessage());
                }
                hr.setCode(ErrorCode.CODE_SUCCESS);
            }
        } catch (Exception e) {
            super.procException(hr, e);
        }
        return hr;
    }
}
